import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';

import fetch from 'API/fetch';

import { withRouter } from 'react-router';
import { Spin } from 'antd';
import EventStatistical from './EventStatistical';
import EventDetail from './EventDetail';
import RaskSelect from '../../../components/RaskSelect';
import Label from '../../../components/Label';
import TrendChart from './TrendChart';
import s from './SecurityEvent.module.css';
import { datetime } from '../../../../common/formatter';

function SecurityEvent({
	className,
	// match: {
	// 	params: { jobId },
	// },
	jobId,
	getDropdownRef,
	result,
	prevResult,
}) {
	const [dateRask, setDateRask] = React.useState({ detectTime: 'last', detectType: 'last' });
	const [pdata, setData] = React.useState({});
	const [tableData, setTableData] = React.useState([]);
	const [loading, setLoading] = React.useState(false);
	const getdata = async ({
		Type = 'securityEvent',
		range = 'range',
		startTime,
		endTime,
	}) => {
		if (!jobId) return false
		setLoading(true);
		let url = `/api/v2/repodatas/report-task?jobId=${jobId}&taskType=${Type}&range=${range}`;
		if (range === 'range') {
			url += `&startTime=${new Date(startTime).toISOString()}
			&endTime=${new Date(endTime).toISOString()}`;
		} else {
			url += `&limit=10`;
		}
		const res = await fetch(url, {
			method: 'GET',
		}).catch(err => {
			console.error(err);
			return {};
		}).finally(() => {
			setLoading(false);
		});
		setData(Object.assign({}, res));
		if (range === 'range') {
			setTableData(res.TaskData);
		} else {
			setTableData(res.TaskData.length > 0 ? [res.TaskData[0]] : []);
		}
		setLoading(false);
	};

	const handleDateRask = val => {
		setDateRask(val);
		const obj = {
			range: val.detectTime || 'range',
		};
		if (val.detectTime === 'prev') {
			setTableData([pdata.TaskData[1]]);
			return false;
		}
		if (obj.range === 'range') {
			obj.startTime = val.dateRange[0];
			obj.endTime = val.dateRange[1];
		}
		getdata(obj);
	};

	const date =
		dateRask?.detectTime === 'last' ? result?.endTime : prevResult?.endTime;
	React.useMemo(() => {
		getdata({ range: 'last' });
	}, []);
	return (
		<div className={cn(className, s.securityEvent)}>
			<div className={s.head}>
				<div className={s.title}>
					<Label className={s.label}>安全事件</Label>
					{dateRask?.detectTime && (
						<span className={s.date}>{datetime(date)}</span>
					)}
				</div>

				<RaskSelect
					value={dateRask}
					onChange={handleDateRask}
					resultLength={pdata?.TaskData?.length || 0}
				/>
			</div>
			<Spin spinning={loading}>
				<TrendChart
					detectTime={dateRask?.detectTime}
					tasks={pdata?.TaskData || []}
					dateRask={dateRask}
					jobId={jobId}
				/>
				<EventStatistical
					tasks={tableData}
					detectTime={dateRask?.detectTime}
					result={result}
					prevResult={prevResult}
				/>
				<EventDetail
					getDropdownRef={getDropdownRef}
					tasks={tableData}
					detectTime={dateRask?.detectTime}
					result={result}
					prevResult={prevResult}
				/>
			</Spin>
		</div>
	);
}

SecurityEvent.propTypes = {
	className: PropTypes.string,
	match: PropTypes.shape({
		params: PropTypes.shape({
			jobId: PropTypes.string,
		}),
	}),
	jobId: PropTypes.string,
	getDropdownRef: PropTypes.func,
	result: PropTypes.shape({
		endTime: PropTypes.object,
		target: PropTypes.string,
		result: PropTypes.shape({
			warningCount: PropTypes.number,
			warnings: PropTypes.shape({
				category: PropTypes.string,
				affects: PropTypes.string,
				detail: PropTypes.object,
			}),
		}),
	}),
	prevResult: PropTypes.shape({
		endTime: PropTypes.object,
		target: PropTypes.string,
		result: PropTypes.shape({
			warningCount: PropTypes.number,
			warnings: PropTypes.shape({
				category: PropTypes.string,
				affects: PropTypes.string,
				detail: PropTypes.object,
			}),
		}),
	}),
};

SecurityEvent.defaultProps = {
	className: s.securityEvent,
};

export default withRouter(SecurityEvent);
